package com.cos.hospital.ui.main;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.QueryType;
import com.cos.hospital.code.helper.KTextWatcher;
import com.cos.hospital.code.helper.MyOnFreshListener;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.PatientListBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.model.event.DoSearchEvent;
import com.cos.hospital.model.event.ReceptionPersonNumEvent;
import com.cos.hospital.model.event.SearchContentEvent;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.main.adapter.ReceptionAdapter;
import com.cos.hospital.ui.patient.PatientInfoActivity;
import com.cos.hospital.ui.patient.SearchAcitvity;
import com.cos.hospital.ui.patient.SendMessageActivity;
import com.cos.hospital.ui.record.RecordEditActivity;
import com.cos.hospital.widget.MyDividerDecoration;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;
import com.jude.utils.JUtils;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 接诊管理  病历 Medical record
 */
public class ReceptionFragment extends MainFragment {

    @BindView(R.id.springView)
    SpringView springView;
    @BindView(R.id.rc)
    RecyclerView rc;
    private List<PatientListBean.ItemsBean> list;
    private BaseQuickAdapter adapter;
    private int pageIndex = 1;
    private int searchResultOldPositon = -1;
    private int queryType;

    public ReceptionFragment(int queryType) {
        this.queryType = queryType;
    }

    @Override
    protected int layout() {
        return R.layout.frag_reception;
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        springView.setHeader(new DefaultHeader(context));
        list = new ArrayList<>();
        adapter = new ReceptionAdapter(list);
        adapter.openLoadAnimation();
        rc.setLayoutManager(new LinearLayoutManager(context));
        adapter.setEmptyView(R.layout.lay_empty, rc);
        rc.addItemDecoration(new MyDividerDecoration(Color.TRANSPARENT, JUtils.dip2px(8)));
        rc.setAdapter(adapter);
    }

    @Override
    protected void logic() {
        springView.setListener(new MyOnFreshListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                getList();
            }
        });
        adapter.setOnItemClickListener((adapter, view, position) -> toPatientInfo(position));
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.tv_write://编辑病历
                    writeRecords(position);
                    break;
                case R.id.tv_send:
                    sendMessage(position);
                    break;
            }
        });
        adapter.setOnLoadMoreListener(() -> {
            pageIndex++;
            getList();
        }, rc);
        springView.callFreshDelay(200);
    }

    private void getList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keyword", "");
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("pageIndex", pageIndex);
        jsonObject.addProperty("pageSize", 10);
        jsonObject.addProperty("queryType", queryType);
        ReceptionPersonNumEvent receptionPersonNumEvent = new ReceptionPersonNumEvent();
        receptionPersonNumEvent.queryType = queryType;
        UHttp.start(getServes().getVisitingList(jsonObject), "接诊管理列表", new HttpMsgListener<ResultBean<PatientListBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
                receptionPersonNumEvent.perosnNum = 0;
            }

            @Override
            public void onFinish() {
                springView.onFinishFreshAndLoadDelay();
            }

            @Override
            public void onSuccess(ResultBean<PatientListBean> dto) {
                if (dto.isSuccess()) {
                    PatientListBean resultBean = dto.getResult();
                    if (resultBean != null) {

                        int pageIndex = resultBean.getPageIndex();
                        int pageSize = resultBean.getPageSize();
                        int recordCount = resultBean.getRecordCount();
                        if (pageIndex == 1) {
                            searchResultOldPositon = -1;
                            list.clear();
                            adapter.notifyDataSetChanged();
                        }
                        List<PatientListBean.ItemsBean> itemsBeanList = resultBean.getItems();
                        if (itemsBeanList != null && itemsBeanList.size() != 0) {
                            list.addAll(itemsBeanList);
                        }
                        int totalPageCount = MyUtil.getInstance().getTotalPageCount(pageSize, recordCount);
                        if (totalPageCount <= pageIndex) {
                            adapter.loadMoreEnd();
                        } else {
                            adapter.loadMoreComplete();
                        }
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
                receptionPersonNumEvent.perosnNum = adapter.getData().size();
                EventBus.getDefault().post(receptionPersonNumEvent);
            }
        });
    }

    private void reception(int fldPatientId, int fldSignId) {
        ProgressDialog.getInstance().startProgressDialog(context);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldPatientId", fldPatientId);
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("fldEditId", SPUtil.getUserId());
        jsonObject.addProperty("fldMedicalFlag", 0);//初复诊标识 初诊 = 0,复诊 = 1
        jsonObject.addProperty("fldSignId", fldSignId);
        UHttp.start(getServes().saveMedical(jsonObject), "病历保存(可同时签到接诊)", new HttpMsgListener<ResultBean<Integer>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<Integer> dto) {
                if (dto.isSuccess()) {
                    Intent intent = new Intent(context, RecordEditActivity.class);
                    intent.putExtra(Code.SP.ID, dto.getResult());
                    startActivity(intent);
                    context.sendBroadcast(new Intent(Code.Broadcast.CutoverToReception));
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void toPatientInfo(int position) {
        PatientListBean.ItemsBean itemsBean = list.get(position);
        Intent intent = new Intent(context, PatientInfoActivity.class);
        intent.putExtra(Code.SP.ID, itemsBean.getFldPatientId());
        intent.putExtra(Code.SP.FLDSTATE, itemsBean.getFldState());
        intent.putExtra(Code.SP.FLDMEDICALHISTORYID, itemsBean.getFldMedicalHistoryId());
        intent.putExtra(Code.SP.FLDDOCTORID, itemsBean.getFldDoctorId());
        intent.putExtra(Code.SP.FLDSIGNID, itemsBean.getFldSignId());
        startActivity(intent);
    }

    private void writeRecords(int position) {
        PatientListBean.ItemsBean itemsBean = list.get(position);
        int fldState = itemsBean.getFldState();
        if (fldState != 2) {//患者签到状态，0：无状态，1：候诊中（患者签到），2：已接诊（患者已接诊）
            reception(itemsBean.getFldPatientId(), itemsBean.getFldSignId());
            return;
        }
        Intent intent = new Intent(context, RecordEditActivity.class);
        intent.putExtra(Code.SP.ID, itemsBean.getFldMedicalHistoryId());
        startActivity(intent);
    }

    private void sendMessage(int position) {
        PatientListBean.ItemsBean itemsBean = list.get(position);
        Intent intent = new Intent(context, SendMessageActivity.class);
        intent.putExtra(Code.SP.ID, itemsBean.getFldPatientId());
        startActivity(intent);
    }

    private void doSearch(String content) {
        MyUtil.getInstance().closeInputMethod(getActivity());
        for (int position = 0; position < list.size(); position++) {
            PatientListBean.ItemsBean itemsBean = list.get(position);
            String fldPatientName = itemsBean.getFldPatientName();
            String fldMedicalNum = itemsBean.getFldMedicalNum();
            String fldPatientPhone = itemsBean.getFldPatientPhone();
            if (fldPatientName.equals(content) || fldMedicalNum.equals(content) || fldPatientPhone.equals(content)) {
                searchResultOldPositon = position;
                changeItem(itemsBean, true);
                ((LinearLayoutManager) rc.getLayoutManager()).scrollToPositionWithOffset(position, 0);
                return;
            }
        }

        Intent intent = new Intent(context, SearchAcitvity.class);
        intent.putExtra(Code.SP.CONTENT, content);
        startActivity(intent);
    }

    private void changeItem(PatientListBean.ItemsBean itemsBean, boolean searchResult) {
        itemsBean.setSearchResult(searchResult);
        adapter.notifyItemChanged(searchResultOldPositon);
    }


    @Override
    protected void refresh() {
        if (springView != null) {
            springView.callFreshDelay(200);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateInfo(DoSearchEvent event) {
        if (event != null) {
            if (event.queryType == QueryType.UN_RECEPTION) {
                doSearch(event.content);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateInfo(SearchContentEvent event) {
        if (event != null) {
            if (event.queryType == QueryType.UN_RECEPTION) {
                if (event.txtEnd.length() == 0) {
                    if (searchResultOldPositon == -1) {
                        return;
                    }
                    if (list.size() == 0) {
                        return;
                    }
                    PatientListBean.ItemsBean itemsBean = list.get(searchResultOldPositon);
                    if (itemsBean == null) {
                        return;
                    }
                    changeItem(itemsBean, false);
                    searchResultOldPositon = -1;
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
